<template>
  <div class="p-6">
    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
      <div
        v-for="(card, index) in statsCards"
        :key="index"
        class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 border border-gray-200 dark:border-gray-700"
      >
        <div class="flex items-center justify-between mb-4">
          <div :class="['w-12 h-12 rounded-lg flex items-center justify-center', card.bgColor]">
            <Icon :name="card.icon" :class="['w-6 h-6', card.iconColor]" />
          </div>
          <div v-if="card.growth !== undefined" :class="['text-sm font-medium flex items-center gap-1', card.growth >= 0 ? 'text-green-600' : 'text-red-600']">
            <Icon :name="card.growth >= 0 ? 'heroicons:arrow-trending-up' : 'heroicons:arrow-trending-down'" class="w-4 h-4" />
            <span>{{ Math.abs(card.growth) }}%</span>
          </div>
        </div>
        <div>
          <div class="text-2xl font-bold text-gray-900 dark:text-white">
            {{ card.value }}
          </div>
          <div class="text-sm text-gray-500 dark:text-gray-400 mt-1">
            {{ card.label }}
          </div>
        </div>
      </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
      <!-- 访问趋势图表 -->
      <div class="lg:col-span-2 bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 border border-gray-200 dark:border-gray-700">
        <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">访问趋势</h3>
        <div class="h-80">
          <canvas ref="trendsChart"></canvas>
        </div>
      </div>

      <!-- 热门工具排行 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 border border-gray-200 dark:border-gray-700">
        <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">热门工具 TOP 10</h3>
        <div class="space-y-3">
          <div
            v-for="(tool, index) in popularTools"
            :key="tool.id"
            class="flex items-center gap-3 p-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
          >
            <div class="flex-shrink-0 w-8 h-8 flex items-center justify-center rounded-full bg-gradient-to-br from-blue-500 to-purple-600 text-white text-sm font-bold">
              {{ index + 1 }}
            </div>
            <div v-if="tool.logo" class="w-8 h-8 rounded overflow-hidden">
              <img :src="getImageUrl(tool.logo)" :alt="tool.name" class="w-full h-full object-cover" />
            </div>
            <div class="flex-1 min-w-0">
              <div class="text-sm font-medium text-gray-900 dark:text-white truncate">
                {{ tool.name }}
              </div>
              <div class="text-xs text-gray-500 dark:text-gray-400">
                {{ formatNumber(tool.views) }} 次浏览
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 最近活动 -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 border border-gray-200 dark:border-gray-700">
      <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">最近活动</h3>
      <div class="space-y-4">
        <div
          v-for="(activity, index) in recentActivities"
          :key="index"
          class="flex items-start gap-3 pb-4 border-b border-gray-100 dark:border-gray-700 last:border-0"
        >
          <div :class="['w-10 h-10 rounded-full flex items-center justify-center', activity.type === 'review' ? 'bg-blue-100 dark:bg-blue-900/30' : 'bg-green-100 dark:bg-green-900/30']">
            <Icon
              :name="activity.type === 'review' ? 'heroicons:chat-bubble-left' : 'heroicons:shopping-cart'"
              :class="['w-5 h-5', activity.type === 'review' ? 'text-blue-600 dark:text-blue-400' : 'text-green-600 dark:text-green-400']"
            />
          </div>
          <div class="flex-1">
            <p class="text-sm text-gray-900 dark:text-white">
              <span class="font-medium">{{ activity.user }}</span>
              <span class="text-gray-500 dark:text-gray-400">{{ activity.action }}</span>
              <span class="font-medium">{{ activity.target }}</span>
            </p>
            <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
              {{ formatTime(activity.time) }}
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { Chart, registerables } from 'chart.js'

// 注册Chart.js组件
Chart.register(...registerables)

definePageMeta({
  layout: 'admin',
  middleware: ['auth'],
})

const $api = useNuxtApp().$api
const { getImageUrl } = useImageUrl()

// 统计卡片数据
const statsCards = ref([
  {
    label: '总浏览量',
    value: '0',
    icon: 'heroicons:eye',
    bgColor: 'bg-blue-100 dark:bg-blue-900/30',
    iconColor: 'text-blue-600 dark:text-blue-400',
    growth: 0,
  },
  {
    label: '工具数量',
    value: '0',
    icon: 'heroicons:cube',
    bgColor: 'bg-purple-100 dark:bg-purple-900/30',
    iconColor: 'text-purple-600 dark:text-purple-400',
    growth: 0,
  },
  {
    label: '用户数量',
    value: '0',
    icon: 'heroicons:users',
    bgColor: 'bg-green-100 dark:bg-green-900/30',
    iconColor: 'text-green-600 dark:text-green-400',
    growth: 0,
  },
  {
    label: '订单数量',
    value: '0',
    icon: 'heroicons:shopping-cart',
    bgColor: 'bg-orange-100 dark:bg-orange-900/30',
    iconColor: 'text-orange-600 dark:text-orange-400',
  },
])

const popularTools = ref<any[]>([])
const recentActivities = ref<any[]>([])
const trendsChart = ref<HTMLCanvasElement | null>(null)
let chartInstance: Chart | null = null

// 加载统计数据
const loadStats = async () => {
  try {
    const data = await $api('/stats/overview') as any
    
    statsCards.value[0]!.value = formatNumber(data.totalViews)
    statsCards.value[0]!.growth = data.viewsGrowth
    statsCards.value[1]!.value = formatNumber(data.totalTools)
    statsCards.value[1]!.growth = data.toolsGrowth
    statsCards.value[2]!.value = formatNumber(data.totalUsers)
    statsCards.value[2]!.growth = data.usersGrowth
    statsCards.value[3]!.value = formatNumber(data.totalOrders)
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 加载访问趋势
const loadTrends = async () => {
  try {
    const data = await $api('/stats/trends') as any
    
    if (trendsChart.value) {
      const ctx = trendsChart.value.getContext('2d')
      if (ctx) {
        chartInstance = new Chart(ctx, {
          type: 'line',
          data: {
            labels: data.map((d: any) => d.date),
            datasets: [
              {
                label: '浏览量',
                data: data.map((d: any) => d.views),
                borderColor: 'rgb(59, 130, 246)',
                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                tension: 0.4,
              },
              {
                label: '用户数',
                data: data.map((d: any) => d.users),
                borderColor: 'rgb(168, 85, 247)',
                backgroundColor: 'rgba(168, 85, 247, 0.1)',
                tension: 0.4,
              },
            ],
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                position: 'bottom',
              },
            },
            scales: {
              y: {
                beginAtZero: true,
              },
            },
          },
        })
      }
    }
  } catch (error) {
    console.error('加载趋势数据失败:', error)
  }
}

// 加载热门工具
const loadPopularTools = async () => {
  try {
    const data = await $api('/stats/popular-tools') as any
    popularTools.value = data
  } catch (error) {
    console.error('加载热门工具失败:', error)
  }
}

// 加载最近活动
const loadRecentActivities = async () => {
  try {
    const data = await $api('/stats/recent-activities') as any
    recentActivities.value = data
  } catch (error) {
    console.error('加载最近活动失败:', error)
  }
}

// 格式化数字
const formatNumber = (num: number) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'w'
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

// 格式化时间
const formatTime = (time: string | Date) => {
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return date.toLocaleDateString()
}

onMounted(async () => {
  await Promise.all([
    loadStats(),
    loadTrends(),
    loadPopularTools(),
    loadRecentActivities(),
  ])
})

// 组件卸载时销毁图表
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.destroy()
  }
})
</script>



